import MapFeature from "./MapFeature";
import * as events from '../event';
import * as mapUtil from '../util'; 
import * as ftypes from '../featureTypes'
import  styles from '../styles';
import { message } from "ant-design-vue";
import {Style,Fill,Stroke, Text} from 'ol/style';
import * as api from '../../../util/api';
import Feature from 'ol/Feature';
import {colorRgb,createImgStyle} from '../util'
import imgurl from '@/assets/map/roomCenter.png'
import {Point,Polygon} from 'ol/geom'
import Base from './base'
import { mapManager } from "../MapManager";


/**
 *  房间信息
 */
class Room extends MapFeature{ 
 
    static ROOM_INDEX = 0;

    constructor(f){
        super(f);
    } 

    /**
     * 开始标记地块
     */
    static beginDraw(){ 
        MapFeature.innerDraw({ftype:ftypes.ROOM,style:styles.drawRoomStyle},(evt)=>{
           
            var base = mapUtil.tunnelInfoInPolygon(evt.feature,mapManager.current.layers.baseSource);
            if(base == null){
                message.error("房间需要规划在基地中!");
                evt.feature.set("deleted",true); //标记已经删除，后面添加到source后再删除
                mapManager.clearDrawSource();
                return ;
            }
            var baseFeature = new Base(base);

            var room = new Room(evt.feature);
            room.setId(Room.ROOM_INDEX);
            room.setName('');
            room.setArea(mapUtil.formatArea(evt.feature.getGeometry()));
            room.setViewColor(evt.feature.getStyle().getStroke().getColor());
            room.setOpacity('0.5');
            room.setIndex(Room.ROOM_INDEX);
            room.setBaseId(baseFeature.getId()); 
            Room.ROOM__INDEX++;
            events.fire(events.types.onAddRoom,{
                type:'create',
                data:room
            });   
            
        }); 
    } 
    
    /**
     * 开始编辑
     */
    doEdit(){ 
        //通知事件
        events.fire(events.types.onAddRoom,{type:'update',data:this});
        var _this = this;
        MapFeature.editFeature(this.feature,(evt)=>{
            var feature_temp = evt.features.getArray()[0];
            var base = mapUtil.tunnelInfoInPolygon(feature_temp, mapManager.getLayers().baseSource);
            if(base == null){ 
                message.error("房间需要规划在基地中!");
                return false;
            } 
            
            //保存截图
            //saveCanvasImg(function(){}); 

            //通知更新 
            events.fire(events.types.onAddRoom,{
                type:'update',
                data:_this
            });
        });
     }

    

    /**
     * 初始化数据
     */
    static initData(){
        
        var scale = MapFeature.zoomScale(17);
      	

        api.get(api.ZYGL_ROOM_LIST,(resp)=>{
            var fields = resp.data;
             //加载数据
             for(var i = 0,j = fields.length ; i < j ; i++ ){
                var field = fields[i];
                if(typeof(field.coordinateGroup) == "undefined" ||  field.coordinateGroup == "" 
                    ||  field.coordinateGroup == null){
                    continue;
                }
                var coordinateGroup = null;
                try{
                    coordinateGroup = JSON.parse(field.coordinateGroup); 
                }catch(e){coordinateGroup = null;}
                
                console.log('加载房间')

                if(coordinateGroup == null) continue; 

                var polygon = new Feature({
                        ftype : ftypes.ROOM,
                        geometry: new Polygon(coordinateGroup.coordinates),
                        name: field.name
                });

                var fieldFeature = new Room(polygon);
                fieldFeature.setId("tunnel_info_" + i)
                fieldFeature.setBaseId(field.baseInfo.id);
                fieldFeature.setName(field.name);
                fieldFeature.setViewColor(field.viewColor);
                fieldFeature.setArea(field.areaNumber);
                fieldFeature.setOpacity(field.opacity);
                fieldFeature.setFieldInfo(field);
                fieldFeature.setType(field.type);
                mapManager.getLayers().roomSource.addFeature(polygon);


                //中心点圆图
				var center = new Feature({
						ftype : ftypes.ROOM_CENTER,
						index_ : i,
						imgurl : imgurl,
				        geometry: new Point(polygon.getGeometry().getInteriorPoint().getCoordinates())
				});
				center.setId("tunnel_info_" + i);
				var centerStyle = createImgStyle(imgurl);
				scale = scale == -1?0:scale;
 				centerStyle.getImage().setScale(scale);
				center.setStyle(centerStyle);
                mapManager.getLayers().roomCenterSource.addFeature(center);

                //文字
				var wenzi =  new Feature({
						ftype : ftypes.ROOM_CENTER_TEXT,
						index_ : i,
						tunnel_info_id_ : field.id,
						name_ : field.name,
				        geometry: new Point(polygon.getGeometry().getInteriorPoint().getCoordinates())
				});
				wenzi.setId("tunnel_info_" + i);
                    //if(tunnel_info.gdFlag == 0)
                    //TODO 已经归档的添加到归档的layer
                    mapManager.getLayers().roomTextSource.addFeature(wenzi);

                        
                   
                    
                //设置样式
                var color = field.viewColor == "" || field.viewColor == null ? "#ffffff" : field.viewColor;
                var style = new  Style({
                        stroke: new  Stroke({
                            color: color,
                            width: 1
                            }),
                        fill: new  Fill({
                                color: "rgba("+colorRgb(color)+", "+field.opacity+")"
                            }),
                        text: new Text({
                            font:'12px sans-serif',
                            text:field.name
                        })
                });
                fieldFeature.setStyle(style);
            }
 
			Room.setFieldTextVisible(mapManager.current.omap.getView().getZoom()); 
            Room.ROOM_INDEX = fields.length; 
        });
    }

    textStyleCache={};

    /**设置地块文字是否显示 和字体大小
	 * 小于18隐藏 
	 * @param zoom
	 */
    static setFieldTextVisible(zoom){
        var tunnelFS = [14,16,22];
        var layers = mapManager.getLayers();
		if(zoom < 18){
			mapManager.getLayers().fieldInfoTextVector.setVisible(false);
		}else{
			layers.fieldInfoTextVector.setVisible(true);
			if(zoom == 18){
				var temp = tunnelFS[0]+"px 宋体";
				for(var style in layers.fieldTextStyleCache){
					var text = layers.fieldTextStyleCache[style].getText()
					text.setFont(temp);
					text.setOffsetY("15");
				}
			}else if(zoom == 19){
				  temp = tunnelFS[1]+"px 宋体";
				for(  style in layers.fieldTextStyleCache){
					  text = layers.fieldTextStyleCache[style].getText()
					text.setFont(temp);
					text.setOffsetY("30");
				}
				setTimeout(function(){
					var temp = tunnelFS[1]+"px 宋体";
					var zoom = mapManager.current.omap.getView().getZoom();
					for(var style in layers.fieldTextStyleCache){
						var text = layers.fieldTextStyleCache[style].getText()
						text.setFont(temp);
						text.setOffsetY("30");
					}
				}, 100);
			}else if(zoom > 19){
				  temp = tunnelFS[2]+"px 宋体";
				for(  style in layers.fieldTextStyleCache){
					  text = layers.fieldTextStyleCache[style].getText()
					text.setFont(temp);
					text.setOffsetY("30");
				}
			}
		}
	}

    /**
     *  ajax 保存数据
     */
    save(data){
       var layers = mapManager.getLayers();
       this.innerSave('/api/zygl/field/save',data,(resp)=>{

        this.setName(data.name);
        this.setArea(data.muNumber) 
        this.setOpacity(data.opacity);
        this.setViewColor(data.viewColor) 
        var fieldId = resp.data.id; 
        this.feature.set("field_id_",fieldId); 
        this.feature.set("field",resp.data); 
         

        var style = this.feature.getStyle(); 
        style.getStroke().setLineDash(null);
        this.feature.setStyle(style);
        this.feature.setId('field_'+fieldId); 
        layers.roomSource.addFeature(this.feature);

        //添加中心点的图标
        var center = layers.roomCenterSource.getFeatureById(this.feature.getId());
        if(center == null){
            center = new Feature({
                ftype : ftypes.ROOM_CENTER,
                imgurl : imgurl,
                geometry: new Point(this.feature.getGeometry().getInteriorPoint().getCoordinates())
            });
            center.setId("tunnel_info_" + fieldId);
            var centerStyle = createImgStyle(imgurl,1);

            var scale = MapFeature.zoomScale(mapManager.current.omap.getView().getZoom());
            centerStyle.getImage().setScale(scale);
            center.setStyle(centerStyle);
            layers.roomCenterSource.addFeature(center);
            center.changed();

            console.log('add room center style ...')
            console.log(center)
    
            var wenzi =  new Feature({
                ftype : ftypes.ROOM_CENTER_TEXT,
                index_ : this.feature.get("tunnel_info_index_"),
                tunnel_info_id_ : fieldId,
                name_ : this.getName(),
                geometry: new Point(this.feature.getGeometry().getInteriorPoint().getCoordinates())
            });
            wenzi.setId("tunnel_info_" + fieldId);
            layers.roomTextSource.addFeature(wenzi);
            this.feature.changed();  
        } 

       });
                
    }

    setFieldInfo(fieldInfo){
        this.feature.set("field_info_",fieldInfo);
    }

    setType(t){
        this.feature.set("type_",t);
    }
    getType(){
        return this.feature.get("type_");
    }
}

export default Room;